SPB Git

Repository Public

route.ts 8.4 KB 127 lines typescript

1import fs from "node:fs";2import path from "node:path";3import { Readable } from "node:stream";4import { pipeline } from "node:stream/promises";5import { authStillValid, TOKEN } from "@/server/relay/access";6import { enabled, hlsBase, limits, playbackBase, relayDir } from "@/server/relay/config";7import { getRelay } from "@/server/relay/relays";8import { close, lookup, touch } from "@/server/relay/sessions";910export const dynamic = "force-dynamic";1112// /relay/<session token>/… — the only door to the relay engine. MediaMTX listens on the loopback interface; every13// playlist and segment goes through here, for a session that exists, has not expired and whose sign-in is still valid.14// The token is in the path so that the relative addresses of the playlists stay inside the session.1516const deny = (status: number, error: string) => new Response(JSON.stringify({ error }), { status, headers: { "content-type": "application/json; charset=utf-8", "cache-control": "no-store" } });17const FILE = /^[A-Za-z0-9_-]{1,120}\.(m3u8|ts|mp4|m4s)$/;18const TYPES: Record<string, string> = { m3u8: "application/vnd.apple.mpegurl", ts: "video/mp2t", mp4: "video/mp4", m4s: "video/iso.segment" };1920// Outgoing bandwidth limit per session (0 = none): data is released at the configured rate, with one second of burst.21type G = typeof globalThis & { __sptvRelayPace?: Map<string, number> };22const pace = () => ((globalThis as G).__sptvRelayPace ??= new Map());23function meter(sessionId: string, kbps: number): TransformStream<Uint8Array, Uint8Array> {24  return new TransformStream({25    async transform(chunk, ctl) {26      touch(sessionId, chunk.byteLength);27      if (kbps > 0) {28        const t = Date.now(); const due = Math.max(pace().get(sessionId) ?? 0, t - 1000) + (chunk.byteLength * 8) / kbps;29        pace().set(sessionId, due);30        if (due > t) await new Promise((r) => setTimeout(r, Math.min(5000, due - t)));31      }32      ctl.enqueue(chunk);33    },34  });35}3637// --- timeshift clips ------------------------------------------------------------------------------------------------------38type GC = typeof globalThis & { __sptvClips?: Map<string, Promise<string | null>> };39const clips = () => ((globalThis as GC).__sptvClips ??= new Map());40const clipDir = () => path.join(relayDir(), "clips");41function sweepClips() {42  try { for (const f of fs.readdirSync(clipDir())) { const p = path.join(clipDir(), f); if (Date.now() - fs.statSync(p).mtimeMs > 15 * 60_000) fs.rmSync(p, { force: true }); } } catch { /* nothing yet */ }43}44function clip(relayId: string, start: number, duration: number): Promise<string | null> {45  const key = `${relayId}-${start}-${duration}`; const file = path.join(clipDir(), `${key}.mp4`);46  if (fs.existsSync(file)) return Promise.resolve(file);47  let job = clips().get(key);48  if (!job) {49    job = (async () => {50      fs.mkdirSync(clipDir(), { recursive: true, mode: 0o700 }); sweepClips();51      const q = new URLSearchParams({ path: relayId, start: new Date(start).toISOString(), duration: String(duration), format: "mp4" });52      const r = await fetch(`${playbackBase()}/get?${q}`, { signal: AbortSignal.timeout(120_000) }).catch(() => null);53      if (!r?.ok || !r.body) return null;54      const tmp = `${file}.part`;55      try { await pipeline(Readable.fromWeb(r.body as never), fs.createWriteStream(tmp, { mode: 0o600 })); fs.renameSync(tmp, file); return file; }56      catch { fs.rmSync(tmp, { force: true }); return null; }57    })().finally(() => clips().delete(key));58    clips().set(key, job);59  }60  return job;61}62function sendRange(req: Request, file: string, sessionId: string): Response {63  const size = fs.statSync(file).size; const m = /^bytes=(\d*)-(\d*)$/.exec(req.headers.get("range") ?? "");64  let from = 0, to = size - 1;65  if (m) { if (m[1] === "") { from = Math.max(0, size - Number(m[2])); } else { from = Number(m[1]); if (m[2]) to = Math.min(size - 1, Number(m[2])); } }66  if (from > to || from >= size) return new Response(null, { status: 416, headers: { "content-range": `bytes */${size}` } });67  const body = Readable.toWeb(fs.createReadStream(file, { start: from, end: to })) as unknown as ReadableStream<Uint8Array>;68  const headers = new Headers({ "content-type": "video/mp4", "accept-ranges": "bytes", "content-length": String(to - from + 1), "cache-control": "private, no-store" });69  if (m) headers.set("content-range", `bytes ${from}-${to}/${size}`);70  return new Response(body.pipeThrough(meter(sessionId, limits().outKbps)), { status: m ? 206 : 200, headers });71}7273export async function GET(req: Request, ctx: { params: Promise<{ path: string[] }> }) {74  const [token, ...rest] = (await ctx.params).path;75  if (!token || !TOKEN.test(token)) return deny(404, "Introuvable");76  const s = lookup(token);77  if (!s) return deny(410, "Session de lecture expirée");78  if (!authStillValid(s.auth)) { close(s.id, "connexion révoquée"); return deny(401, "Authentification requise"); }79  if (!enabled()) return deny(503, "Le moteur de relais est désactivé");80  const relay = getRelay(s.relay_id);81  if (!relay) return deny(404, "Relais introuvable");82  touch(s.id, 0);83  const url = new URL(req.url);8485  if (rest[0] === "timeshift") {86    if (!relay.record) return deny(403, "Le différé n'est pas autorisé pour cette source");87    if (rest[1] === "list") {88      const r = await fetch(`${playbackBase()}/list?path=${relay.id}`, { signal: AbortSignal.timeout(5000) }).catch(() => null);89      const spans = r?.ok ? (await r.json() as { start: string; duration: number }[]) : [];90      return new Response(JSON.stringify({ spans: spans.map((x) => ({ start: Date.parse(x.start), duration: x.duration })), windowSec: limits().timeshiftMin * 60 }), { headers: { "content-type": "application/json", "cache-control": "no-store" } });91    }92    if (rest[1] === "get.mp4") {93      // The player names an absolute instant, so that the several range requests Safari makes for one clip all94      // designate the same recording. The clip is written once to a private temporary file and served with ranges.95      const windowMs = limits().timeshiftMin * 60_000;96      const start = Number(url.searchParams.get("start")); const duration = Math.max(2, Math.min(windowMs / 1000, Number(url.searchParams.get("duration")) || 0));97      if (!Number.isFinite(start) || start < Date.now() - windowMs - 60_000 || start > Date.now() || !duration) return deny(400, "Instant hors de la fenêtre du différé");98      const file = await clip(relay.id, Math.round(start), Math.round(duration));99      if (!file) return deny(404, "Aucun enregistrement pour cet instant");100      return sendRange(req, file, s.id);101    }102    return deny(404, "Introuvable");103  }104105  const file = rest.join("/");106  const m = FILE.exec(file); if (!m) return deny(404, "Introuvable");107  // MediaMTX identifies each player by a session of its own, created with the master playlist and carried in the addresses it writes.108  const mtxSession = url.searchParams.get("session");109  const upstream = `${hlsBase()}/${relay.id}/${file}${file === "index.m3u8" ? "?cookieCheck=1" : mtxSession && /^[0-9a-f-]{36}$/.test(mtxSession) ? `?session=${mtxSession}` : ""}`;110  const ctl = new AbortController(); req.signal.addEventListener("abort", () => ctl.abort());111  // While a relay starts, the first request waits for the source; if the ingest gives up meanwhile, answer at once.112  let failed: string | null = null;113  const watch = file === "index.m3u8" ? setInterval(() => { const r = getRelay(relay.id); if (r?.state === "failed") { failed = r.last_error ?? "Le relais n'a pas pu démarrer"; ctl.abort(); } }, 500) : undefined;114  let r: Response | null = null;115  try { r = await fetch(upstream, { signal: ctl.signal, redirect: "manual" }); } catch { /* aborted or engine down */ } finally { clearInterval(watch); }116  if (failed) return deny(503, failed);117  if (!r) return deny(502, "Le moteur de relais ne répond pas");118  if (r.status !== 200 || !r.body) {119    const now = getRelay(relay.id);120    return deny(r.status === 404 ? 503 : r.status >= 500 ? 502 : r.status, now?.state === "failed" ? now.last_error ?? "Le relais n'a pas pu démarrer" : "Le flux n'est pas encore disponible");121  }122  const headers = new Headers({ "content-type": TYPES[m[1]], "cache-control": m[1] === "m3u8" ? "no-store" : "private, max-age=30", "x-content-type-options": "nosniff" });123  const kbps = limits().outKbps;124  const len = r.headers.get("content-length"); if (len && !kbps) headers.set("content-length", len);125  return new Response(r.body.pipeThrough(meter(s.id, m[1] === "m3u8" ? 0 : kbps)), { status: 200, headers });126}127
Files main
Menu

Theme